package com.bootdo.system.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.system.domain.BizCustomerDO;
import com.bootdo.system.domain.BizCustomerFullVO;
import com.bootdo.system.domain.BizCustomerIncomeVO;
import com.bootdo.system.domain.BizCustomerPayDO;
import com.bootdo.system.service.BizCustomerPayService;
import com.bootdo.system.service.BizCustomerService;
import com.bootdo.system.vo.ExcelPropertyIndexModel;

/**
 * 客户信息表
 * 
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2019-06-25 10:10:25
 */

@Controller
@RequestMapping("/system/bizCustomer")
public class BizCustomerController {
    @Autowired
    private BizCustomerService bizCustomerService;

    @Autowired
    private BizCustomerPayService payService;

    @GetMapping()
    @RequiresPermissions("system:bizCustomer:bizCustomer")
    String BizCustomer() {
        return "system/bizCustomer/bizCustomer";
    }

    @GetMapping("/xufei/{custId}")
    @RequiresPermissions("system:bizCustomer:xufei")
    String Xufei(@PathVariable("custId") String custId, Model model) {
        model.addAttribute("custId", custId);
        return "system/bizCustomer/xufei";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("system:bizCustomer:bizCustomer")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<BizCustomerDO> bizCustomerList = bizCustomerService.list(query);
        int total = bizCustomerService.count(query);
        PageUtils pageUtils = new PageUtils(bizCustomerList, total);
        return pageUtils;
    }

    @GetMapping("/add")
    @RequiresPermissions("system:bizCustomer:add")
    String add() {
        return "system/bizCustomer/add";
    }

    @GetMapping("/edit/{tid}")
    @RequiresPermissions("system:bizCustomer:edit")
    String edit(@PathVariable("tid") String tid, Model model) {
        BizCustomerFullVO fullVO = new BizCustomerFullVO();
        BizCustomerDO bizCustomer = bizCustomerService.get(tid);
        BizCustomerPayDO payDO = payService.getByCustId(tid);

        List<BizCustomerPayDO> history = payService.history(tid);
        BeanUtils.copyProperties(bizCustomer, fullVO);

        fullVO.setServDdyfpFee(payDO.getServDdyfpFee());
        fullVO.setServDlfpFee(payDO.getServDlfpFee());
        fullVO.setServDzsbFee(payDO.getServDzsbFee());
        fullVO.setServLsjzFee(payDO.getServLsjzFee());
        fullVO.setServRkqjbrFee(payDO.getServRkqjbrFee());
        fullVO.setServZjwhFee(payDO.getServZjwhFee());
        fullVO.setServZzsbFee(payDO.getServZzsbFee());
        fullVO.setOtherFee(payDO.getOtherFee());

        model.addAttribute("bizCustomer", fullVO);
        model.addAttribute("history", history);

        return "system/bizCustomer/edit";
    }

    @GetMapping("/view/{tid}")
    @RequiresPermissions("system:bizCustomer:view")
    String view(@PathVariable("tid") String tid, Model model) {
        BizCustomerFullVO fullVO = new BizCustomerFullVO();
        BizCustomerDO bizCustomer = bizCustomerService.get(tid);
        BizCustomerPayDO payDO = payService.getByCustId(tid);

        List<BizCustomerPayDO> history = payService.history(tid);
        BeanUtils.copyProperties(bizCustomer, fullVO);

        fullVO.setServDdyfpFee(payDO.getServDdyfpFee());
        fullVO.setServDlfpFee(payDO.getServDlfpFee());
        fullVO.setServDzsbFee(payDO.getServDzsbFee());
        fullVO.setServLsjzFee(payDO.getServLsjzFee());
        fullVO.setServRkqjbrFee(payDO.getServRkqjbrFee());
        fullVO.setServZjwhFee(payDO.getServZjwhFee());
        fullVO.setServZzsbFee(payDO.getServZzsbFee());
        fullVO.setOtherFee(payDO.getOtherFee());

        model.addAttribute("bizCustomer", fullVO);
        model.addAttribute("history", history);

        return "system/bizCustomer/view";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("system:bizCustomer:add")
    public R save(BizCustomerFullVO bizCustomer) {
        String tid = UUID.randomUUID().toString().replaceAll("-", "");
        BizCustomerDO newCustomer = new BizCustomerDO();
        BeanUtils.copyProperties(bizCustomer, newCustomer);
        newCustomer.setTid(tid);
        newCustomer.setCustStatus(1);
        if (!"other".equals(bizCustomer.getBeAnnual())) {
            //失效日期，增加一年
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String from = bizCustomer.getJoinDate();
            try {
                String end = DateUtils.dateAddMonth(simpleDateFormat.parse(from), 12);
                newCustomer.setExpireDate(end);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        BizCustomerPayDO payDO = new BizCustomerPayDO();

        BeanUtils.copyProperties(bizCustomer, payDO);
        payDO.setTid(UUID.randomUUID().toString().replaceAll("-", ""));
        payDO.setCustId(tid);
        payDO.setPayDate(bizCustomer.getJoinDate());
        payDO.setExpireDate(newCustomer.getExpireDate());
        payDO.setActiveStatus(1);
        payService.save(payDO);

        if (bizCustomerService.save(newCustomer) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/saveXufei")
    @RequiresPermissions("system:bizCustomer:xufei")
    public R saveXufei(BizCustomerPayDO payDO) {
        //将其它所有记录置为无效
        payService.updateOtherInvidate(payDO.getCustId());
        payDO.setTid(UUID.randomUUID().toString().replaceAll("-", ""));
        payDO.setActiveStatus(1);

        BizCustomerDO customerDO = new BizCustomerDO();
        customerDO.setTid(payDO.getCustId());
        customerDO.setJoinDate(payDO.getPayDate());
        customerDO.setAnnualFee(payDO.getAnnualFee());
        customerDO.setCustStatus(1);
        if (!"other".equals(payDO.getBeAnnual())) {
            //失效日期，增加一年
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String from = payDO.getPayDate();
            try {
                String end = DateUtils.dateAddMonth(simpleDateFormat.parse(from), 12);
                customerDO.setExpireDate(end);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        bizCustomerService.update(customerDO);

        if (payService.save(payDO) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("system:bizCustomer:edit")
    public R update(BizCustomerDO bizCustomer) {
        bizCustomerService.update(bizCustomer);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("system:bizCustomer:remove")
    public R remove(String tid) {
        if (bizCustomerService.remove(tid) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("system:bizCustomer:batchRemove")
    public R remove(@RequestParam("ids[]") String[] tids) {
        bizCustomerService.batchRemove(tids);
        return R.ok();
    }

    /**
     * 删除
     */
    @GetMapping("/export")
    @ResponseBody
    @RequiresPermissions("system:bizCustomer:export")
    public void export(HttpServletRequest request, HttpServletResponse response,
            String custName, String contract, String endDate, String beginDate,
            String servType, String custStatus) {
        Map<String, Object> params = new HashMap<>();
        params.put("custName", custName);
        params.put("contract", contract);
        params.put("endDate", endDate);
        params.put("servType", servType);
        params.put("custStatus", custStatus);
        //查询列表数据
        List<ExcelPropertyIndexModel> bizCustomerList = bizCustomerService.queryData2Export(params);
        String path = "E://crm-files-notdelete//customer_crm.xlsx";
        //        String path = "/Users/apple/78.xlsx";
        OutputStream out;
        try {
            out = new FileOutputStream(path);

            try {
                ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
                //写第一个sheet, sheet1  数据全是List<String> 无模型映射关系
                Sheet sheet1 = new Sheet(1, 0, ExcelPropertyIndexModel.class);
                writer.write(bizCustomerList, sheet1);
                writer.finish();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        String fileName = "雷行科技-CRM系统客户数据-" + simpleDateFormat.format(new Date()) + ".xlsx";
        File file = new File(path);
        if (file.exists()) {
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

    @GetMapping("/incomeStaticsEntry")
    @RequiresPermissions("system:bizCustomer:incomeStaticsEntry")
    String incomeStaticsEntry() {
        return "system/bizCustomer/bizCustomerIncomeStatics";
    }

    @ResponseBody
    @GetMapping("/incomeStatics")
    @RequiresPermissions("system:bizCustomer:incomeStaticsEntry")
    public PageUtils incomeStatics(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<BizCustomerIncomeVO> bizCustomerList = bizCustomerService.incomeStatics(query);
        int total = 1;
        PageUtils pageUtils = new PageUtils(bizCustomerList, total);
        return pageUtils;
    }
}
